package com.hj.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class PdfUtils {

    private final Logger logger = LoggerFactory.getLogger(PdfUtils.class);

    private final String imageFileSuffix = ".jpg";

    @Value("${server.tomcat.uri-encoding:UTF-8}")
    private String uriEncoding;

    public List<String> pdf2jpg(String pdfFilePath, String pdfName, String baseUrl) {
        String pdfFolder = pdfName.substring(0, pdfName.length() - 4);
        String imagefolder = pdfFilePath.substring(0, pdfFilePath.lastIndexOf("."));
        String urlPrefix = null;
        try {
            urlPrefix = baseUrl
                + URLEncoder.encode(URLEncoder.encode(pdfFolder, uriEncoding).replaceAll("\\+", "%20"), uriEncoding);
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException", e);
            urlPrefix = baseUrl + pdfFolder;
        }
        List<String> imageUrls = getImageUrlList(urlPrefix, imagefolder, pdfFolder);
        if (!CollectionUtils.isEmpty(imageUrls)) {
            return imageUrls;
        }
        try {
            File pdfFile = new File(pdfFilePath);
            PDDocument doc = PDDocument.load(pdfFile);
            int pageCount = doc.getNumberOfPages();
            PDFRenderer pdfRenderer = new PDFRenderer(doc);

            File path = new File(imagefolder);
            if (!path.exists()) {
                path.mkdirs();
            }
            String imageFilePath;
            for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
                imageFilePath = imagefolder + File.separator + pdfFolder + pageIndex + imageFileSuffix;
                BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 105, ImageType.RGB);
                ImageIOUtil.writeImage(image, imageFilePath, 105);
                imageUrls.add(urlPrefix + "/" + pdfFolder + pageIndex + imageFileSuffix);
            }
            doc.close();
        } catch (IOException e) {
            logger.error("Convert pdf to jpg exception, pdfFilePath：{}", pdfFilePath, e);
        }
        return imageUrls;
    }

    /**
     * @author dehui dou
     * @description 获取已转换图片地址
     * @date 2020/9/25 16:27
     * @params [urlPrefix, imagefolder, filterName]
     */
    private List<String> getImageUrlList(String urlPrefix, String imagefolder, String filterName) {
        List<String> imageUrls = new ArrayList<>();
        File file = new File(imagefolder);
        if (file.exists() && file.isDirectory()) {
            FilenameFilter fileNameFilter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    if (name.lastIndexOf('.') > 0) {
                        int lastIndex = name.lastIndexOf('.');
                        String str = name.substring(lastIndex);
                        if (imageFileSuffix.equals(str) && name.startsWith(filterName)) {
                            return true;
                        }
                    }
                    return false;
                }
            };
            String[] arr = file.list(fileNameFilter);
            for (String imageName : arr) {
                imageUrls.add(urlPrefix + "/" + imageName);
            }
        }
        return imageUrls;
    }
}
